'use strict'

import axios from 'axios'
import { Loading } from 'element-ui'
import { getToken } from '@/utils/auth'
import { devBaseURL } from '@/api'

let loading
function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
function endLoading() {
  loading.close()
}

axios.interceptors.request.use(config => {
  startLoading()
  config.headers.Authorization = getToken()
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  endLoading()
  return response
}, error => {
  endLoading()
  return Promise.resolve(error.response)
})

function checkStatus(response) {
  // loading
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response.data
    // 如果不需要除了data之外的数据，可以直接 return response.data
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  }
}

export function post(url, data) {
  return axios({
    method: 'post',
    baseURL: devBaseURL,
    url,
    data: data,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  }).then(
    (response) => {
      return checkStatus(response)
    }
  )
}

export function get(url, params) {
  return axios({
    method: 'get',
    baseURL: devBaseURL,
    url,
    params, // get 请求时带的参数
    timeout: 10000
  }).then(
    (response) => {
      return checkStatus(response)
    }
  )
}

export function _get(url, param) {
  return axios({
    method: 'get',
    baseURL: devBaseURL,
    url: url + '/' + param,
    timeout: 10000
  }).then(
    (response) => {
      return checkStatus(response)
    }
  )
}

export default {
  post(url, data) {
    return axios({
      method: 'post',
      baseURL: devBaseURL,
      url,
      data: data,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    )
  },
  get(url, params) {
    return axios({
      method: 'get',
      baseURL: devBaseURL,
      url,
      params, // get 请求时带的参数
      timeout: 10000
    }).then(
      (response) => {
        return checkStatus(response)
      }
    )
  },
  _get(url, param) {
    return axios({
      method: 'get',
      baseURL: devBaseURL,
      url: url + '/' + param,
      timeout: 10000
    }).then(
      (response) => {
        return checkStatus(response)
      }
    )
  }
}
